package com.example.light.system.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.light.system.common.Result;
import com.example.light.system.dto.allUserList;
import com.example.light.system.entity.user;
import com.example.light.system.entity.userRole;
import com.example.light.system.mapper.UserMapper;
import com.example.light.system.mapper.UserRoleMapper;
import com.example.light.system.service.impl.IUserService;
import com.example.light.system.vo.insertUser;
import com.example.light.system.vo.searchUser;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class userService extends ServiceImpl<UserMapper, user> implements IUserService {
    @Resource
    UserMapper userMapper;
    @Resource
    UserRoleMapper userRoleMapper;

    /**
     * 查询所有用户
     *
     * @return
     */
    public Result<ArrayList<allUserList>> searchAllUser(){
        // 查询所有用户
        List<user> userList = userMapper.selectList(null);
        ArrayList<allUserList> arrayList = new ArrayList<>();
        Iterator<user> iterator = userList.iterator();
        // 逻辑错误需要判断是否当前还存在用户
        while (iterator.hasNext()){
            user next = iterator.next();
            allUserList allUserList = new allUserList();
            // 查询所有用户角色归属
            Integer userId = next.getUserId();
            ArrayList list = userMapper.searchUserRoleName(userId);
            allUserList.setUserAccount(next.getUserAccount());
            allUserList.setUserName(next.getUserName());
            allUserList.setUserPassword(next.getUserPassword());
            allUserList.setUserPhone(next.getUserPhone());
            allUserList.setUserStatus(next.getUserStatus());
            if (next.getUserNote().length() == 0){
                allUserList.setUserNote("暂无备注");
            }else {
                allUserList.setUserNote(next.getUserNote());
            }
            if (list.size() != 0){
                allUserList.setRoleNameSet(list);
            }else {
                list.add(0,"暂无绑定角色");
                allUserList.setRoleNameSet(list);
            }
            arrayList.add(allUserList);
        }
        return Result.success(arrayList);
    }

    /**
     * 新增用户
     * @param insertUser
     * @return
     */
    public Result<String> insertUser(insertUser insertUser){
        // 查询当前用户是否已经存在
        QueryWrapper<user> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", insertUser.getUserAccount());
        user userInfo = userMapper.selectOne(queryWrapper);
        // insert变量用于检查用户是否成功新增
        Integer addUserInsert;
        // 当前用户如果存在则返回错误信息
        // 新用户不存在则创建新用户
        if (userInfo != null){
            return Result.fail("账号已存在");
        }else {
            // 接受前需要进行是否为空的验证，后续完善中
            user addUser = new user();
            userRole userRole = new userRole();
            addUser.setUserAccount(insertUser.getUserAccount());
            addUser.setUserName(insertUser.getUserName());
            addUser.setUserPhone(insertUser.getUserPhone());
            addUser.setUserPassword(insertUser.getUserPassword());
            addUser.setUserStatus(insertUser.getUserStatus());
            addUser.setUserNote(insertUser.getUserNote());
            // 新增新用户
            addUserInsert = userMapper.insert(addUser);
        }
        // 如果用户添加成功，则获取用户id并完成用户与角色之间的绑定
        if (addUserInsert == 1){
            QueryWrapper<user> wrapper = new QueryWrapper<>();
            wrapper.eq("user_account", insertUser.getUserAccount());
            user selectUser = userMapper.selectOne(wrapper);
            Integer integer = userRoleMapper.batchInsertUserRole(selectUser.getUserId(), insertUser.getRoleIdSet());
            if (integer > 0){
                return Result.success("用户添加成功");
            }else {
                return Result.fail("用户角色映射添加失败");
            }
        }else {
            return Result.fail("用户添加失败");
        }
    }

    /**
     * 编辑用户
     * @param insertUser
     * @return
     */
    public Result<String> editUser(insertUser insertUser){
        // 查询用户是否存在
        String userAccount = insertUser.getUserAccount();
        QueryWrapper<user> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        user selectUser = userMapper.selectOne(queryWrapper);
        if (selectUser != null){
            // 判断用户需要修改的参数，并存入user对象中
            user user = new user();
            user.setUserId(selectUser.getUserId());
            if (insertUser.getUserName() != null && insertUser.getUserName().length() != 0){
                user.setUserName(insertUser.getUserName());
            }
            if (insertUser.getUserPassword() != null && insertUser.getUserPassword().length() != 0){
                user.setUserPassword(insertUser.getUserPassword());
            }
            if (insertUser.getUserPhone() != null && insertUser.getUserPhone().length() != 0){
                user.setUserPhone(insertUser.getUserPhone());
            }
            if (insertUser.getUserStatus() != null){
                user.setUserStatus(insertUser.getUserStatus());
            }
            if (insertUser.getUserNote().length() != 0){
                user.setUserNote(insertUser.getUserNote());
            }
            // 修改用户基础信息
            userMapper.updateById(user);
        }
        // 查询用户是否与角色关联
        QueryWrapper<userRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", selectUser.getUserId());
        List<userRole> userRoles = userRoleMapper.selectList(wrapper);
        // 如果有关联，则删除原有用户与角色映射关系，没有则新增
        if (userRoles.size() != 0){
            if (insertUser.getRoleIdSet().size() != 0){
                // 删除角色映射并添加新映射
                userRoleMapper.delete(wrapper);
                userRoleMapper.batchInsertUserRole(selectUser.getUserId(), insertUser.getRoleIdSet());
            }
            return Result.success("编辑成功");
        }else {
            if (insertUser.getRoleIdSet().size() != 0){
                userRoleMapper.batchInsertUserRole(selectUser.getUserId(), insertUser.getRoleIdSet());
            }
            return Result.success("编辑成功");
        }
    }

    /**
     * 删除用户
     *
     * @param userAccount
     * @return
     */
    public Result<String> deleteUser(String userAccount) {
        // 查询并获取用户ID
        QueryWrapper<user> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        user user = userMapper.selectOne(queryWrapper);
        Integer userId = user.getUserId();
        // 通过ID删除用户表数据
        Integer delete = userMapper.deleteById(user);
        // 通过ID删除用户角色关联表数据
        QueryWrapper<userRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<userRole> userRoles = userRoleMapper.selectList(wrapper);
        // 用户存在角色关联则删除关联，不存在则直接判断用户基础信息是否删除
        Integer deleteUserRole;
        if (delete != 0 && userRoles.size() != 0){
            deleteUserRole = userRoleMapper.delete(wrapper);
            return deleteUserRole != 0?Result.success("删除成功"):Result.fail("删除失败");
        }
        return delete != 0?Result.success("删除成功"):Result.fail("删除失败");
    }

    // 查询用户
    public Result<ArrayList<allUserList>> searchUser(searchUser searchUser){
        // 查询用户
        ArrayList<user> userList = new ArrayList<>();
        // 如果账号完整，则通过账号精准查询
        // 如果账号为空或者不完整，则通过名字模糊查询
        if (searchUser.getUserAccount() == null || searchUser.getUserAccount().length() == 11){
            userList = userMapper.searchUser(searchUser.getUserAccount(), null);
        }else {
            userList = userMapper.searchUser(null, searchUser.getUserName());
        }
        // 角色匹配与用户数据整理
        ArrayList<allUserList> arrayList = new ArrayList<>();
        Iterator<user> iterator = userList.iterator();
        while (iterator.hasNext()){
            user next = iterator.next();
            allUserList allUserList = new allUserList();
            // 查询所有用户角色归属
            Integer userId = next.getUserId();
            ArrayList list = userMapper.searchUserRoleName(userId);
            allUserList.setUserAccount(next.getUserAccount());
            allUserList.setUserName(next.getUserName());
            allUserList.setUserPassword(next.getUserPassword());
            allUserList.setUserPhone(next.getUserPhone());
            allUserList.setUserStatus(next.getUserStatus());
            if (next.getUserNote().length() == 0){
                allUserList.setUserNote("暂无备注");
            }else {
                allUserList.setUserNote(next.getUserNote());
            }
            if (list.size() != 0){
                allUserList.setRoleNameSet(list);
            }else {
                list.add(0,"暂无绑定角色");
                allUserList.setRoleNameSet(list);
            }
            arrayList.add(allUserList);
        }
        return Result.success(arrayList);
    }
}
